package com.sql.common.util;


import com.sql.common.intc.ParseUtilConvert;

/**
 * Created by www on 2016/12/18.
 */
public class ParseUtil {
    public static <T>T parse(Object value, Class<T> clazz, ParseUtilConvert pc){
        if(clazz == null){
            throw new RuntimeException("未知的类型转换");
        }
        if(pc == null){
            if(clazz.equals(Boolean.class) || clazz.equals(boolean.class)){
                if(value==null || value.toString().trim().length()==0||value.toString().equals("false") || value.toString().equals("0")){
                    return (T) Boolean.valueOf(false);
                }else{
                    return (T) Boolean.valueOf(true);
                }
            }
            if(value == null || value.toString().trim().length()==0){
                return null;
            }
            if(value.getClass().equals(clazz) || clazz.isAssignableFrom(value.getClass())){
                return (T)value;
            }else{
                if(clazz.equals(String.class)){
                    return (T)value.toString();
                }
                try{
                    if(clazz.equals(Integer.class) || clazz.equals(int.class)){
                        return (T) Integer.valueOf(value.toString());
                    }else if(clazz.equals(Byte.class) || clazz.equals(byte.class)){
                        return (T) Byte.valueOf(value.toString());
                    }else if(clazz.equals(Short.class) || clazz.equals(short.class)){
                        return (T) Short.valueOf(value.toString());
                    }else if(clazz.equals(Float.class) || clazz.equals(float.class)){
                        return (T) Float.valueOf(value.toString());
                    }else if(clazz.equals(Double.class) || clazz.equals(double.class)){
                        return (T) Double.valueOf(value.toString());
                    }else if(clazz.equals(Long.class) || clazz.equals(long.class)){
                        return (T) Long.valueOf(value.toString());
                    }else if(clazz.equals(Character.class) || clazz.equals(char.class)){
                        return (T) Character.valueOf(value.toString().charAt(0));
                    }
                }catch(Exception e){
                    System.err.println(e.getMessage());
                }
            }
        }else{
            T v = (T) pc.convert(clazz,value);
            if(v == null) return parse(value,clazz,null);
            return v;
        }
        return null;
    }

    public static boolean packageEquals(Object o1, Object o2){
        if(o1!=null) return o1.equals(o2);
        if(o2!=null) return o2.equals(o1);
        return true;
    }
}
